package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.MatMapper;
import com.indusfo.spc.mapper.MatTypeMapper;
import com.indusfo.spc.pojo.MatType;
import com.indusfo.spc.service.MatTypeService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XCommonUtil;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author louk
 * @date 2019/11/19 9:32
 */
@Service
public class MatTypeServiceImpl implements MatTypeService {


    //日志记录
    private static final Logger logger = LoggerFactory.getLogger(MatTypeServiceImpl.class);

    @Resource
    private MatTypeMapper mtypeXOMapper;

    @Resource
    private MatMapper materialXOMapper;

    /**
     * 分页查询
     * @param mtypeXO
     * @return
     */
    @Override
    public JSONObject listMtypeXO(MatType mtypeXO) {
        try {


            // 获取一页显示多少行
            Integer pagesize = mtypeXO.getPagesize();
            // 获取查询第几页
            Integer pageindex = mtypeXO.getPageindex();

            //初始值


            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                mtypeXO.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法
            if(new Integer(0).equals(mtypeXO.getMatTypeId())){
                mtypeXO.setMatTypeId(null);
            }
            List<MatType> listForPage = mtypeXOMapper.selectAllMatType(mtypeXO);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有查询到相关数据",listForPage, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count = mtypeXOMapper.countMatType(mtypeXO);
                return JSONObject.oK(listForPage, count);
            }
            return JSONObject.oK(listForPage.get(0));



        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 新增
     * @param mtypeXO
     * @return
     */
    @Override
    public JSONObject insertMatType(MatType mtypeXO) {
        try{
            //判断其是否存在父ID
            if(mtypeXO.getMatTypePid()==null  || "".equals(mtypeXO.getMatTypePid())){
                mtypeXO.setMatTypePid(0);
            }
            if(mtypeXO.getDataState()==null || "".equals(mtypeXO.getDataState())){
                mtypeXO.setDataState(1);
            }
            /**
             * @author: louk
             * @param:
             * @Return:
             * @Description: :检查物料类型名称长度以及
             * @date: 2019/9/6 9:53
             *
             */
            checkElement(mtypeXO);
            JSONObject checkParamsNotRepeatJson = checkParamsNotRepeat(mtypeXO);
            if (checkParamsNotRepeatJson.isOk()) {


                validate(mtypeXO);
                Integer row = mtypeXOMapper.insertSelective(mtypeXO);
                if(row == 0) {
                    throw new ModifyFailedException("新增物料类型失败");
                }
                List<MatType> mtypeXOS = mtypeXOMapper.selectAllMatType(mtypeXO);
                Integer mtypeId=row;
                if(mtypeXOS!=null && mtypeXOS.size()>0){
                    mtypeId = mtypeXOS.get(0).getMatTypeId();
                }
                return JSONObject.oK("新增成功", mtypeId);


            }else {
                throw new ParamsErrorException(checkParamsNotRepeatJson.getMsg());
            }


        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 编辑
     * @param mtypeXO
     * @return
     */
    @Override
    public JSONObject updateMatType(MatType mtypeXO) {
        try{
            //判断其是否存在父ID
            if(mtypeXO.getMatTypePid()==null  || "".equals(mtypeXO.getMatTypePid())){
                mtypeXO.setMatTypePid(0);
            }
            if(mtypeXO.getDataState()==null || "".equals(mtypeXO.getDataState())){
                mtypeXO.setDataState(1);
            }
            if(mtypeXO.getMatTypeId()==null || "".equals(mtypeXO.getMatTypeId())){
                throw new ModifyFailedException("请选择物料类别");
            }
            /**
             * @author: louk
             * @param:
             * @Return:
             * @Description: :检查物料类型名称长度以及
             * @date: 2019/9/6 9:53
             *
             */
            checkElement(mtypeXO);
            JSONObject checkParamsNotRepeatJson = checkParamsNotRepeat(mtypeXO);
            if (checkParamsNotRepeatJson.isOk()) {


                validate(mtypeXO);
                Integer row = mtypeXOMapper.updateByPrimaryKeySelective(mtypeXO);
                if(row == 0) {
                    throw new ModifyFailedException("更新物料类型失败");
                }
                return JSONObject.oK("更新成功", row);

            }else {
                throw new ParamsErrorException(checkParamsNotRepeatJson.getMsg());
            }


        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 删除
     * @param deteMtypeXO
     * @param lDataState
     * @return
     */
    @Override
    public JSONObject deleteMtypeXO(Integer[] deteMtypeXO, Integer lDataState) {
        try {
            //1.校验
            if(deteMtypeXO == null) {
                throw new ParamsErrorException("物料类型id不能为空");
            }
            if(lDataState == null) {
                throw new ParamsErrorException("物料类型状态不能为空");
            }
            int flag = mtypeXOMapper.countByMatTypePids(deteMtypeXO);
            if(flag>0){
                throw new ParamsErrorException("该物料类下仍包含子类无法删除");
            }
            int countMaterial = materialXOMapper.ListMatByMatTypeId(deteMtypeXO);
            if(countMaterial>0){
                throw new ParamsErrorException("该物料类下包含物料信息无法删除");
            }
            int row = mtypeXOMapper.deleteMatType(deteMtypeXO,lDataState);
            String msg = "";
            switch (lDataState) {
                case 1:
                    msg = "启用";
                    break;
                case 2:
                    msg = "删除";
                    break;
                case 3:
                    msg = "停用";
            }

            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (lDataState) {
                    case 1:
                        throw new ModifyFailedException(msg+"失败");
                    case 2:
                        throw new ModifyFailedException(msg+"失败");
                    case 3:
                        throw new ModifyFailedException(msg+"失败");
                }
            }
            Integer row1 = materialXOMapper.deleteBymatTypeIds(deteMtypeXO);

            return JSONObject.oK(msg+"成功", row);
        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    /**
     * 树
     * @param mtypeXO
     * @return
     */
    @Override
    public JSONObject treeMtypeXO(MatType mtypeXO) {
        List<XTreeNode> tree = null;
        try {
            tree = new ArrayList<>();
            List<XTreeNode> nodes = new ArrayList<>();
            //获取所有的物料类别进行构建树
            List<MatType> list = mtypeXOMapper.selectTreeMatType(mtypeXO);
            //构建一个标志,当其不为空的时候树上增加全部
            if(mtypeXO.getFlag()!=null){
                XTreeNode node0=new XTreeNode();
                MatType mx=new MatType();
                mx.setMatTypeId(0);
                mx.setMatTypePid(0);
                mx.setMatTypeName("全部");
                node0.setId(mx.getMatTypeId());
                node0.setpId(mx.getMatTypePid() == 0 ? null : mx.getMatTypePid());
                node0.setOpen(true);

                node0.setTitle(mx.getMatTypeName());
                list.add(0,mx);
            }
            //当标志大于0的时候,将其父的expand改为true,该树改为的selected改为true
            if (null != list) {
                for (MatType matType : list) {
                    XTreeNode node = new XTreeNode();
                    node.setId(matType.getMatTypeId());
                    node.setpId(matType.getMatTypePid() == 0 ? null : matType.getMatTypePid());
                    node.setOpen(true);
                    node.setCode(matType.getMatTypeCode());
                    node.setTitle(matType.getMatTypeName());
                    nodes.add(node);
                }
            }
            if(mtypeXO.getFlag()!=null && mtypeXO.getFlag()>0){
                if(mtypeXO.getFlag()>0){
                    List<XTreeNode> aBoolean = new XTreeUtil().getBoolean(mtypeXO.getFlag(), nodes);
                    //当页面初始化的时候为树的第一个默认是点亮的状态
                    tree = XCommonUtil.getTree(aBoolean, null);
                    return JSONObject.oK(tree);
                }
            }else{
                //当页面初始化的时候为树的第一个默认是点亮的状态
                tree = XCommonUtil.getTree(nodes, null);
                tree.get(0).setSelected(true);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.oK(tree);
    }


    /**
     * 验证重复
     * @param mtypeXO
     * @return
     */
    private JSONObject checkParamsNotRepeat(MatType mtypeXO) {
        try {
            // 判断不良原因类型ID是否传入


            MatType check = new MatType();
            check.setMatTypeName(mtypeXO.getMatTypeName());
            if (mtypeXO.getMatTypeId() != null) {
                // 有SOP基础资料ID为更新操作,调用剔除本条记录是否有重复
                check.setMatTypeId(mtypeXO.getMatTypeId());
                int row = mtypeXOMapper.countParamsNotRepeat(check);
                if (row > 0) {
                    throw new ParamsErrorException("已存在该产品");
                }
            } else {

                int row = mtypeXOMapper.countParamsNotRepeat(check);
                if (row > 0) {
                    throw new ParamsErrorException("已存在该产品");
                }
            }
            return JSONObject.oK();

        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }


    /**
     * 非空判断
     * @param mtypeXO
     */
    private void validate(MatType mtypeXO) {
        //类型名称
        String mtypeXOName =mtypeXO.getMatTypeName();

        if(StringUtils.isEmpty(mtypeXOName)){
            throw new ParamsErrorException("类型名称不能为空");
        }
    }

    /**
     * 检测属性
     * @param mtypeXO
     */
    private  void checkElement(MatType mtypeXO){
        if(StringUtils.isEmpty(mtypeXO.getMatTypeName())){
            throw new ParamsErrorException("物料类别名称不能为空");
        }
        if (("全部").equals(mtypeXO.getMatTypeName())) {
            throw new ParamsErrorException("该物料类别名称已存在");
        }
        if(mtypeXO.getMatTypeName().length()>50){
            throw new ParamsErrorException("物料类别名称不能大于50");
        }
    }
}
